﻿using System;
using System.Data.Entity.Validation;
using System.Linq;
using Biz.EF;
using Biz.EF.Platform.Gxt;
using Hjt212Parser;
using log4net;

namespace Biz.Process
{
    /// <summary>
    /// 负责处理数据指令:2011、2051、2061、2031
    /// </summary>
    public static class ProcessorData4Monitor
    {
        private static ILog Log = LogManager.GetLogger(typeof(ProcessorData4Monitor));
        /// <summary>
        /// 实时数据2011指令处理
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process2011(PlatformGxtContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn)) return;
                //mn = MonitorAndTotalMnMap.GetTotalMnByMonitorMn(mn);
                //if (string.IsNullOrEmpty(mn)) return;
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue) return;
                //1、插入主记录
                xaxis_realtime xaxis = new xaxis_realtime
                {
                    MN = mn,
                    datatime = datatime.Value
                };
                pCtx.xaxis_realtime.Add(xaxis);
                pCtx.SaveChanges();
                //2、插入或更新状态
                var state = pCtx.state_real.FirstOrDefault(t => t.MN.Equals(mn));
                if (state != null)
                {
                    pCtx.state_real.Remove(state);
                    pCtx.SaveChanges();
                }
                state = new state_real();
                state.MN = mn;
                state.datatime = datatime.Value;
                state.id = xaxis.id;
                pCtx.state_real.Add(state);
                pCtx.SaveChanges();
                //3、插入数据
                var factors = Parser.GetPollutantCodes(content);
                foreach (var factor in factors)
                {

                    data_real_time data = new data_real_time
                    {
                        ID = xaxis.id,
                        pollutant = factor,
                        rtd = Parser.GetFloatByKey(factor + "-Rtd", content)
                    };
                    var oldFactor = Convert.GetOldFactorFromNewFactor(factor);
                    if (oldFactor != null)
                    {
                        data.pollutant = oldFactor;
                    }
                    pCtx.data_real_time.Add(data);
                }
                pCtx.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }
        /// <summary>
        /// 分钟数据2051指令处理
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process2051(PlatformGxtContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn)) return;
                //mn = MonitorAndTotalMnMap.GetTotalMnByMonitorMn(mn);
                //if (string.IsNullOrEmpty(mn)) return;
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue) return;
                //1、插入或更新主记录
                //var begin = new DateTime(datatime.Value.Year, datatime.Value.Month, datatime.Value.Day, datatime.Value.Hour, datatime.Value.Minute, 0);
                //var end = begin.AddMinutes(20);
                //var xaxis = pCtx.xaxis_minute.Where(t => t.MN.Equals(mn))
                //    .FirstOrDefault(t => t.datatime >= begin && t.datatime < end);
                //if (xaxis == null)
                //{
                var xaxis = new xaxis_minute();
                xaxis.MN = mn;
                xaxis.datatime = datatime.Value;
                pCtx.xaxis_minute.Add(xaxis);
                pCtx.SaveChanges();
                //}
                //2、插入或更新状态
                var state = pCtx.state_minute.FirstOrDefault(t => t.MN.Equals(mn));
                if (state != null)
                {
                    pCtx.state_minute.Remove(state);
                    pCtx.SaveChanges();
                }
                state = new state_minute();
                state.MN = mn;
                state.datatime = datatime.Value;
                state.id = xaxis.id;
                pCtx.state_minute.Add(state);
                pCtx.SaveChanges();
                //3、插入或更新数据
                var factors = Parser.GetPollutantCodes(content);
                foreach (var factor in factors)
                {
                    var avg = Parser.GetFloatByKey(factor + "-Avg", content);
                    var cou = Parser.GetFloatByKey(factor + "-Cou", content);
                    var min = Parser.GetFloatByKey(factor + "-Min", content);
                    var max = Parser.GetFloatByKey(factor + "-Max", content);
                    if (avg != null && cou != null && min != null && max != null)
                    {
                        var data = pCtx.data_minute.Where(t => t.ID == xaxis.id).FirstOrDefault(t => t.pollutant.Equals(factor));
                        if (data == null)
                        {
                            data = new data_minute();
                            data.ID = xaxis.id;
                            data.pollutant = factor;
                            data.avg = avg.Value;
                            data.cou = cou.Value;
                            data.min = min.Value;
                            data.max = max.Value;
                            var oldFactor = Convert.GetOldFactorFromNewFactor(factor);
                            if (oldFactor != null)
                            {
                                data.pollutant = oldFactor;
                            }
                            pCtx.data_minute.Add(data);
                        }
                    }
                }
                pCtx.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }
        /// <summary>
        /// 小时数据2061指令处理
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process2061(PlatformGxtContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn)) return;
                //mn = MonitorAndTotalMnMap.GetTotalMnByMonitorMn(mn);
                //if (string.IsNullOrEmpty(mn)) return;
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue) return;
                //1、插入或更新主记录
                var begin = new DateTime(datatime.Value.Year, datatime.Value.Month, datatime.Value.Day, datatime.Value.Hour, 0, 0);
                var end = begin.AddHours(1);
                var xaxis = pCtx.xaxis_hour.Where(t => t.MN.Equals(mn))
                    .FirstOrDefault(t => t.datatime >= begin && t.datatime < end);
                //TODO:性能有问题，所以存在就不做任何事情
                if (xaxis != null) return;

                xaxis = new xaxis_hour();
                pCtx.xaxis_hour.Add(xaxis);

                xaxis.MN = mn;
                xaxis.datatime = datatime.Value;
                pCtx.SaveChanges();
                //2、插入或更新状态
                var state = pCtx.state_hour.FirstOrDefault(t => t.MN.Equals(mn));
                if (state != null)
                {
                    pCtx.state_hour.Remove(state);
                    pCtx.SaveChanges();
                }
                state = new state_hour();
                state.MN = mn;
                state.datatime = datatime.Value;
                state.id = xaxis.id;
                pCtx.state_hour.Add(state);
                pCtx.SaveChanges();
                //3、插入或更新数据
                var factors = Parser.GetPollutantCodes(content);
                foreach (var factor in factors)
                {
                    var avg = Parser.GetFloatByKey(factor + "-Avg", content);
                    var cou = Parser.GetFloatByKey(factor + "-Cou", content);
                    if (cou < 0 || cou > MaxCou.HourCou)
                    {
                        cou = 0;
                    }
                    var min = Parser.GetFloatByKey(factor + "-Min", content);
                    var max = Parser.GetFloatByKey(factor + "-Max", content);
                    if (avg != null && cou != null && min != null && max != null)
                    {
                        var data = pCtx.data_hour.Where(t => t.ID == xaxis.id).FirstOrDefault(t => t.pollutant.Equals(factor));
                        if (data == null)
                        {
                            data = new data_hour();
                            pCtx.data_hour.Add(data);
                        }
                        data.ID = xaxis.id;
                        data.pollutant = factor;
                        data.avg = avg.Value;
                        data.cou = cou.Value;
                        data.min = min.Value;
                        data.max = max.Value;
                        var oldFactor = Convert.GetOldFactorFromNewFactor(factor);
                        if (oldFactor != null)
                        {
                            data.pollutant = oldFactor;
                        }
                    }
                }
                pCtx.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }
        /// <summary>
        /// 日数据2031指令处理
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process2031(PlatformGxtContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn)) return;
                //mn = MonitorAndTotalMnMap.GetTotalMnByMonitorMn(mn);
                //if (string.IsNullOrEmpty(mn)) return;
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue) return;
                //1、插入或更新主记录
                var begin = new DateTime(datatime.Value.Year, datatime.Value.Month, datatime.Value.Day, 0, 0, 0);
                var end = begin.AddDays(1);
                var xaxis = pCtx.xaxis_day.Where(t => t.MN.Equals(mn))
                    .FirstOrDefault(t => t.datatime >= begin && t.datatime < end);
                if (xaxis == null)
                {
                    xaxis = new xaxis_day();
                    pCtx.xaxis_day.Add(xaxis);
                }
                xaxis.MN = mn;
                xaxis.datatime = datatime.Value;
                pCtx.SaveChanges();
                //2、插入或更新状态
                var state = pCtx.state_day.FirstOrDefault(t => t.MN.Equals(mn));
                if (state != null)
                {
                    pCtx.state_day.Remove(state);
                    pCtx.SaveChanges();
                }
                state = new state_day();
                state.MN = mn;
                state.datatime = datatime.Value;
                state.id = xaxis.id;
                pCtx.state_day.Add(state);
                pCtx.SaveChanges();
                //3、插入或更新数据
                var factors = Parser.GetPollutantCodes(content);
                foreach (var factor in factors)
                {
                    var avg = Parser.GetFloatByKey(factor + "-Avg", content);
                    var cou = Parser.GetFloatByKey(factor + "-Cou", content);
                    if (cou < 0 || cou > MaxCou.HourCou * 24)
                    {
                        cou = 0;
                    }
                    var min = Parser.GetFloatByKey(factor + "-Min", content);
                    var max = Parser.GetFloatByKey(factor + "-Max", content);
                    if (avg != null && cou != null && min != null && max != null)
                    {
                        var data = pCtx.data_day.Where(t => t.ID == xaxis.id).FirstOrDefault(t => t.pollutant.Equals(factor));
                        if (data == null)
                        {
                            data = new data_day();
                            pCtx.data_day.Add(data);
                        }
                        data.ID = xaxis.id;
                        data.pollutant = factor;
                        data.avg = avg.Value;
                        data.cou = cou.Value;
                        data.min = min.Value;
                        data.max = max.Value;
                        var oldFactor = Convert.GetOldFactorFromNewFactor(factor);
                        if (oldFactor != null)
                        {
                            data.pollutant = oldFactor;
                        }
                    }
                }
                pCtx.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }
    }
}
